<?php
namespace App\Services\Impl;
use App\Services\UserServiceInterface;
use Log;
use Illuminate\Support\Facades\Auth;
use App\Pojo\ResponsePojo;
use App\Constant\HttpStatus;
use App\Library\UserLibraryInterface;
use Illuminate\Support\Facades\Redis;
use App\Models\DawnUser;
final class UserServiceImpl implements UserServiceInterface{

    private $userLibraryInterface;

    public function __construct(UserLibraryInterface $userLibraryInterface)
    {
        $this->userLibraryInterface = $userLibraryInterface;
    }

    public function register($credentials){
        $result = $this->userLibraryInterface->register($credentials);
        if($result){
            return ResponsePojo::success(HttpStatus::OK,HttpStatus::getStatusMessage(HttpStatus::OK));
        }
        return ResponsePojo::error(HttpStatus::EXISTIMG_USER,HttpStatus::getStatusMessage(HttpStatus::EXISTIMG_USER));
    }

    public function login($request, $credentials){
        $adjustedCredentials = ['dawn_name' => $credentials['username'],
        'password' => $credentials['password']];
        $user = DawnUser::where('dawn_name', $credentials['username'])->first();
        if (!$user) {
            return ResponsePojo::error(HttpStatus::UNAUTHORIZED, '用户不存在');
        }
        if($user->dawn_Status == 1){
            return ResponsePojo::error(HttpStatus::UNAUTHORIZED, '用户已禁用');
        }
        if($user->dawn_Status == 3){
            return ResponsePojo::error(HttpStatus::UNAUTHORIZED, '用户不存在');
        }
        if (Auth::attempt($adjustedCredentials)) {
            $request->session()->regenerate();
            return ResponsePojo::success(HttpStatus::OK,HttpStatus::getStatusMessage(HttpStatus::OK));
        }
        return ResponsePojo::error(HttpStatus::UNAUTHORIZED,HttpStatus::getStatusMessage(HttpStatus::UNAUTHORIZED));
    }

    public function logout($request){

        Redis::del('userId:'.Auth::id());

        Auth::logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        

        return ResponsePojo::success(HttpStatus::OK,HttpStatus::getStatusMessage(HttpStatus::OK));
    }


}
